package com.ming_za.od_updater_sdk.server_api;

import com.ming_za.od_updater_sdk.IUpdater;
import com.ming_za.od_updater_sdk.exception.UnConnectServerException;
import com.ming_za.od_updater_sdk.server_api.result_obj.*;
import com.ming_za.od_updater_sdk.server_api.result_obj.data.ResData;
import com.ming_za.od_updater_sdk.obj.ReqValue;
import com.ming_za.od_updater_sdk.obj.Res;
import com.ming_za.od_updater_sdk.server_api.result_obj.data.ResFileInfo;
import com.ming_za.od_updater_sdk.utils.HttpUtils;
import com.ming_za.od_updater_sdk.utils.JsonPackageBuilder;
import com.ming_za.od_updater_sdk.utils.JsonUtils;
import okhttp3.Response;

import java.util.Objects;

/**
 * 默认更新器API
 */
public class DefaultUpdaterAPI implements IUpdaterServer {

    @Override
    public ReqValue<Integer> getConcurrencyCount(IUpdater odUpdater) {

        ReqValue<Integer> result = new ReqValue<>();

        try (Response response = HttpUtils.sendGet(APIUrl.MAX_DOWNLOAD_CONCURRENT, null,odUpdater)) {

            ValueR valueR = JsonUtils.fromJson(Objects.requireNonNull(response.body()).string(), ValueR.class);
            if (valueR.getCode() != 200){
                throw new UnConnectServerException(valueR.getMessage());
            }
            result.setValue(Integer.parseInt(valueR.getData().getValue()));

        } catch (Exception e) {
            odUpdater.getLogger().warn("请求异常-->",e);
            result.setServerAPIState(ServerAPIState.UNABLE_TO_CONNECT);
        }

        return result;
    }

    @Override
    public ReqValue<ResFileInfo> getResFile(Res res,IUpdater odUpdater) {

        ReqValue<ResFileInfo> result = new ReqValue<>();

        try {
            Response response = HttpUtils.sendGet(APIUrl.DOWNLOAD_RES.getUrl() + res.getId(),null,odUpdater);

            long fileSize = Long.parseLong(Objects.requireNonNull(response.header("Content-Length", "-1")));

            if (fileSize == -1) {

                VoidR r = JsonUtils.fromJson(Objects.requireNonNull(response.body()).string(), VoidR.class);

                if (r.getCode() == 30004){
                    result.setServerAPIState(ServerAPIState.MAXIMUM_DOWNLOAD);
                }else {
                    odUpdater.getLogger().warn("无法获取文件数据");
                    result.setServerAPIState(ServerAPIState.UNABLE_TO_CONNECT);
                }
            }else {
                result.setValue(new ResFileInfo(fileSize, Objects.requireNonNull(response.body()).byteStream(),response));
            }
        }catch (Exception e) {
            odUpdater.getLogger().warn("请求异常-->", e);
            result.setServerAPIState(ServerAPIState.UNABLE_TO_CONNECT);
        }
        return result;
    }

    @Override
    public ReqValue<ResData[]> getVersionRes(int version, long labelId, int unpublishKey,IUpdater odUpdater) {

        ReqValue<ResData[]> result = new ReqValue<>();

        JsonPackageBuilder param = new JsonPackageBuilder()
                .put("version",version)
                .put("label",labelId)
                .put("key",unpublishKey);

        try (Response response = HttpUtils.sendGet(APIUrl.RES,param,odUpdater)){

            ResVersionR resVersionR = JsonUtils.fromJson(Objects.requireNonNull(response.body()).string(), ResVersionR.class);
            if (resVersionR.getCode() != 200){
                throw new UnConnectServerException(resVersionR.getMessage());
            }
            result.setValue(resVersionR.getData());

        } catch (Exception e) {
            odUpdater.getLogger().warn("请求异常-->",e);
            result.setServerAPIState(ServerAPIState.UNABLE_TO_CONNECT);
        }

        return result;
    }

    @Override
    public ReqValue<Integer[]> getVersions(int nowVersion,int unpublishKey,IUpdater odUpdater) {

        ReqValue<Integer[]> result = new ReqValue<>();

        JsonPackageBuilder param = JsonPackageBuilder.create()
                .put("version", nowVersion)
                .put("key", unpublishKey);

        try (Response response = HttpUtils.sendGet(APIUrl.VERSIONS,param,odUpdater)){

            VersionsR versions = JsonUtils.fromJson(Objects.requireNonNull(response.body()).string(), VersionsR.class);
            if (versions.getCode() != 200){
                throw new UnConnectServerException(versions.getMessage());
            }
            result.setValue(versions.getData());

        }catch (Exception e) {
            odUpdater.getLogger().warn("请求异常-->",e);
            result.setServerAPIState(ServerAPIState.UNABLE_TO_CONNECT);
        }

        return result;
    }

    @Override
    public ReqValue<Integer> getUnpublishedVersion(int unpublishKey, IUpdater odUpdater) {

        ReqValue<Integer> result = new ReqValue<>();
        result.setValue(0);
        if (unpublishKey == 0){
            return result;
        }

        JsonPackageBuilder param = JsonPackageBuilder.create()
                .put("key", unpublishKey);

        try (Response response = HttpUtils.sendGet(APIUrl.UNPUBLISHED_VERSION,param,odUpdater)){
            VersionR version = JsonUtils.fromJson(Objects.requireNonNull(response.body()).string(), VersionR.class);
            if (version.getCode() != 200){
                throw new UnConnectServerException(version.getMessage());
            }
            result.setValue(version.getData());
        }catch (Exception e) {
            odUpdater.getLogger().warn("请求异常-->",e);
            result.setServerAPIState(ServerAPIState.UNABLE_TO_CONNECT);
        }

        return result;
    }
}
